//
//  ToSayViewController.m
//  xinhua_sx
//
//  Created by 党阳阳 on 14-6-9.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//

#import "ToSayViewController.h"
#import "XHSayViewModel.h"
#import "MBProgressHUD.h"
#import <QuartzCore/QuartzCore.h>
#import "POP.h"


@interface ToSayViewController ()
@property (nonatomic,strong ) UIButton       *jianyi;// 单选框
@property (nonatomic,strong ) UIButton       *fenxiang;
@property (nonatomic,strong ) UIButton       *jubao;
@property (nonatomic,strong ) UIButton       *biaoyang;
@property (nonatomic,strong ) UITextField    *toPeople;// 对谁说
@property (nonatomic,strong ) UIButton       *send;// 发送
@property (nonatomic,strong ) UIButton       *photo;//选取图片
@property (nonatomic,strong ) UITextView     *input;// 要说的话
@property (nonatomic ,strong) UIImage *image;

@property (nonatomic ,strong) XHSayViewModel *sayViewModel;
@property (nonatomic ,strong) NSArray        *pickViewData;
@property (nonatomic ,strong) UIPickerView   *selectPickView;// 人物选取
@property (nonatomic ,strong) UIScrollView   *scrollView;



@end

@implementation ToSayViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        CGRect frame = [[UIScreen mainScreen] bounds];

        self.view.frame = frame;
        UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] init];
        swipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
        [self.view addGestureRecognizer:swipeGesture];
        [[swipeGesture rac_gestureSignal] subscribeNext:^(id x) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        self.titleLable.text = @"我要说";
        
        
        [self.leftButton setImage:[UIImage imageNamed:@"icon_back@2x.png"] forState:UIControlStateNormal];
        [[self.leftButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        self.rightButton.hidden = YES;

        _sayViewModel = [[XHSayViewModel alloc] init];
        [[_sayViewModel getGoalUserId] subscribeNext:^(id x) {
            if (![x isKindOfClass:[NSArray class]]) {
                [self performSelectorOnMainThread:@selector(showMessage:) withObject:x waitUntilDone:YES];
                _pickViewData = [NSArray arrayWithObjects:x, nil];
                
            }else{
                NSArray *array = (NSArray *)x;
                _pickViewData = [NSArray arrayWithArray:array];
                [_selectPickView reloadAllComponents];
                [_selectPickView selectRow:0 inComponent:0 animated:YES];
                _toPeople.text = [[_pickViewData objectAtIndex:0] objectForKey:@"name"];
                
            }
        }];

        CGFloat aY = kIOS_VERSION<7.0?42:62;
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, aY, frame.size.width, frame.size.height-aY)];
        _scrollView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_scrollView];
        
        // 单选框
        
        _jubao = [[UIButton alloc] initWithFrame:CGRectMake(30, 30, 20, 20)];
        _fenxiang = [[UIButton alloc] initWithFrame:CGRectMake(90, 30, 20, 20)];
        _jianyi = [[UIButton alloc] initWithFrame:CGRectMake(150, 30, 20, 20)];
        _biaoyang = [[UIButton alloc] initWithFrame:CGRectMake(215, 30, 20, 20)];

        UILabel *jubao = [[UILabel alloc] initWithFrame:CGRectMake(55, 30, 34, 21)];
        UILabel *fengxiang = [[UILabel alloc] initWithFrame:CGRectMake(115, 30, 34, 21)];
        UILabel *jianyi = [[UILabel alloc] initWithFrame:CGRectMake(175, 30, 34, 21)];
        UILabel *biaoyang = [[UILabel alloc] initWithFrame:CGRectMake(240, 30, 34, 21)];
        
        
        [jubao setFont:[UIFont systemFontOfSize:13.0]];
        [fengxiang setFont:[UIFont systemFontOfSize:13.0]];
        [jianyi setFont:[UIFont systemFontOfSize:13.0]];
        [biaoyang setFont:[UIFont systemFontOfSize:13.0]];
        
        
        [jubao setText:@"举报"];
        [jianyi setText:@"建议"];
        [fengxiang setText:@"分享"];
        [biaoyang setText:@"表扬"];

        
        [_jubao setImage:[UIImage imageNamed:@"checkbox_selected.png"] forState:UIControlStateSelected];
        [_fenxiang setImage:[UIImage imageNamed:@"checkbox_selected.png"] forState:UIControlStateSelected];
        [_jianyi setImage:[UIImage imageNamed:@"checkbox_selected.png"] forState:UIControlStateSelected];
        [_biaoyang setImage:[UIImage imageNamed:@"checkbox_selected.png"] forState:UIControlStateSelected];
        
        [_jubao setImage:[UIImage imageNamed:@"checkbox_unselect.png"] forState:UIControlStateNormal];
        [_fenxiang setImage:[UIImage imageNamed:@"checkbox_unselect.png"] forState:UIControlStateNormal];
        [_jianyi setImage:[UIImage imageNamed:@"checkbox_unselect.png"] forState:UIControlStateNormal];
        [_biaoyang setImage:[UIImage imageNamed:@"checkbox_unselect.png"] forState:UIControlStateNormal];
        
        [_jianyi addTarget:self action:@selector(selectOneButton:) forControlEvents:UIControlEventTouchUpInside];
        [_fenxiang addTarget:self action:@selector(selectOneButton:) forControlEvents:UIControlEventTouchUpInside];
        [_jubao addTarget:self action:@selector(selectOneButton:) forControlEvents:UIControlEventTouchUpInside];
        [_biaoyang addTarget:self action:@selector(selectOneButton:) forControlEvents:UIControlEventTouchUpInside];

    
        [_scrollView addSubview:_fenxiang];
        [_scrollView addSubview:fengxiang];
        [_scrollView addSubview:_biaoyang];
        [_scrollView addSubview:biaoyang];
        [_scrollView addSubview:_jianyi];
        [_scrollView addSubview:jianyi];
        [_scrollView addSubview:jubao];
        [_scrollView addSubview:_jubao];
        
        
        // 对谁说？
        UILabel *toPeople = [[UILabel alloc] initWithFrame:CGRectMake(30, 60, 50, 21)];
        [toPeople setFont:[UIFont systemFontOfSize:13.0]];
        [toPeople setText:@"对谁说:"];
        
        _toPeople = [[UITextField alloc] initWithFrame:CGRectMake(80, 60, 160, 21)];
        [_toPeople setFont:[UIFont systemFontOfSize:13.0]];
        _toPeople.layer.cornerRadius = 5.0f;
        _toPeople.layer.masksToBounds = YES;
        _toPeople.borderStyle = UITextBorderStyleRoundedRect;
        
        _selectPickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, frame.size.height, frame.size.width, 216)];
        _toPeople.delegate = self;
        _selectPickView.delegate = self;
        _selectPickView.dataSource = self;
        _toPeople.inputView = _selectPickView;
        _toPeople.inputAccessoryView = [self inputAccessoryView];
        
        
        [_scrollView addSubview:toPeople];
        [_scrollView addSubview:_selectPickView];
        [_scrollView addSubview:_toPeople];
        
        //要说的话
        _input = [[UITextView alloc] initWithFrame:CGRectMake(30, 90, frame.size.width-60, 120)];
        _input.layer.cornerRadius = 5.0f;
        _input.layer.masksToBounds = YES;
        _input.layer.borderColor = [[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.8]CGColor];
        
        _input.layer.borderWidth = 0.5f;
        _input.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        
        [_scrollView addSubview:_input];
        
        
        
        // 选取图片 提交
        
        _photo = [[UIButton alloc] initWithFrame:CGRectMake(30, 220, 80, 80)];
        [_photo setBackgroundImage:[UIImage imageNamed:@"567.png"] forState:UIControlStateNormal];
        [_photo setTitle:@"选取图片或拍照" forState:UIControlStateNormal];
        
        _send = [[UIButton alloc] initWithFrame:CGRectMake(30, 310, frame.size.width-60, 30)];
         [_send setBackgroundImage:[UIImage imageNamed:@"button_active.png"] forState:UIControlStateNormal];
        [_send setTitle:@"发送" forState:UIControlStateNormal];
        _photo.layer.cornerRadius = 5.0f;
        [_photo addTarget:self action:@selector(pickPhoto:) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *addImage = [[UILabel alloc] initWithFrame:CGRectMake(120, 250, 60, 30)];
        addImage.backgroundColor = [UIColor clearColor];
        addImage.textColor = [UIColor grayColor];
        addImage.text = @"添加图片";
        addImage.font = [UIFont systemFontOfSize:13.0];
        
        [_scrollView addSubview:addImage];
        
        _photo.layer.masksToBounds = YES;
        _send.layer.cornerRadius = 5.0f;
        _send.layer.masksToBounds = YES;
        [[_send rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            
            NSInteger row = [_selectPickView selectedRowInComponent:0];
            
            id goalUserId = [[_pickViewData objectAtIndex:row] objectForKey:@"id"];
            
            id stype;
            if (_biaoyang.selected) {
                 stype = @3;
                
            }else if(_fenxiang.selected){
                 stype = @2;
            
            }else if(_jianyi.selected){
                 stype = @1;
                
            }else if(_jubao.selected){
                
                 stype = @0;
            }else{
            
            
                [self performSelectorOnMainThread:@selector(showMessage:) withObject:@"选择类型" waitUntilDone:YES];
                return ;
            }
        
            if ([[_input text] length]<10) {
                [self performSelectorOnMainThread:@selector(showMessage:) withObject:@"输入小于10字" waitUntilDone:YES];
                return ;

            }
        
            id content = [_input text];
            
            
            [[_sayViewModel sendWithGoalUserId:goalUserId stype:stype content:content image:_image] subscribeNext:^(id x) {
                if ([x isKindOfClass:[NSString class]]) {
                    [self performSelectorOnMainThread:@selector(showMessage:) withObject:x waitUntilDone:YES];
                   
                }
                
                if ([x isKindOfClass:[NSDictionary class]]) {
                    NSString *message = [x objectForKey:@"message"];
                    [self performSelectorOnMainThread:@selector(showMessageThenPOP:) withObject:message
                                        waitUntilDone:YES];
                    butoncl* al = [[butoncl alloc] init];
                    [al postString:@"020"fff:@""];
                    
                }
                
            
            }];
            
            
        }];
        [_scrollView addSubview:_photo];
        [_scrollView addSubview:_send];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_input resignFirstResponder];
    [_toPeople resignFirstResponder];
}

- (void)selectOneButton:(id)sender
{
    UIButton *button = (UIButton *)sender;
    if (button.selected) {
        button.selected = NO;
    }else{
        
        _biaoyang.selected = NO;
        _jianyi.selected = NO;
        _jubao.selected = NO;
        _fenxiang.selected = NO;
        
        button.selected = YES;
        
    }
}
#pragma mark pickView


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}


- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    return [_pickViewData count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
   
    
    return [[_pickViewData objectAtIndex:row] objectForKey:@"name"];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    _toPeople.text = [[_pickViewData objectAtIndex:row] objectForKey:@"name"];

//    [_toPeople resignFirstResponder];
    
    
}


-(UIToolbar *)inputAccessoryView
{
    
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(pickViewDone)];
      UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    toolBar.items = [NSArray arrayWithObjects: flexibleSpace,right,nil];
    
    return toolBar;
    
}

- (void)pickViewDone
{
    [_toPeople resignFirstResponder];
    [_input resignFirstResponder];

}
#pragma mark textfield

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSInteger row = [_selectPickView selectedRowInComponent:0];
    _toPeople.text = [[_pickViewData objectAtIndex:row] objectForKey:@"name"];
}


#pragma mark 提示信息
- (void)showMessage:(NSString *)message
{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = message;
    [self.view addSubview:HUD];
    [HUD showAnimated:YES
  whileExecutingBlock:^{
      sleep(1);
  }
      completionBlock:^{
          [HUD removeFromSuperview];
      }];
    
}

- (void)showMessageThenPOP:(NSString *)message
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 200, 240, 150)];
    label.layer.cornerRadius = 5.0f;
    label.layer.masksToBounds = YES;
    label.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6];
    
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.numberOfLines = 0;
    label.textColor = [UIColor whiteColor];
    [self.view addSubview:label];
    
    POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    anim.fromValue = [NSValue valueWithCGRect:CGRectMake(60, 220, 160, 110)];
    anim.toValue = [NSValue valueWithCGRect:CGRectMake(40, 200, 240, 150)];
    [label pop_addAnimation:anim forKey:@"spring"];
    label.text = message;
    [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(doTimer:) userInfo:nil repeats:NO];
    
    
    
    
}
- (void)doTimer:(NSTimer *)timer
{
    timer = nil;
    [self.navigationController popToRootViewControllerAnimated:YES];

}

#pragma mark 选取图片
- (void)pickPhoto:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"选取图片或拍照"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"从相册选取",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        //拍照
        
        [self pickPhotoWithSource:UIImagePickerControllerSourceTypeCamera];
        return;
    
    }
    if (buttonIndex == 1) {
        // 选取图片
        [self pickPhotoWithSource:UIImagePickerControllerSourceTypePhotoLibrary];
        
        return;
        
    }
    return;
}

- (void)pickPhotoWithSource:(UIImagePickerControllerSourceType )source
{
    //创建图片选择器
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    //指定源类型前，检查图片源是否可用
    if ([UIImagePickerController isSourceTypeAvailable:source])
    {
        //指定源的类型
        imagePicker.sourceType = source;
        
        //在选定图片之前，用户可以简单编辑要选的图片。包括上下移动改变图片的选取范围，用手捏合动作改变图片的大小等。
        imagePicker.allowsEditing = YES;
        
        //实现委托，委托必须实现UIImagePickerControllerDelegate协议，来对用户在图片选取器中的动作
        imagePicker.delegate = self;
        
        //设置完iamgePicker后，就可以启动了。用以下方法将图像选取器的视图“推”出来
        [self presentModalViewController:imagePicker animated:YES];
        
        
    }
    else
    {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:@"相机不能用" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [alert show];
        
    }
}

#pragma  mark UIImagePickerControllerDelegate协议的方法

//用户点击图像选取器中的“cancel”按钮时被调用，这说明用户想要中止选取图像的操作
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}

//用户点击选取器中的“choose”按钮时被调用，告知委托对象，选取操作已经完成，同时将返回选取图片的实例
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    
    //上传图片

    _image= image;
    [_photo setImage:_image forState:UIControlStateNormal];
//    NSLog(@"image %@",image);
    [picker dismissModalViewControllerAnimated:YES];
    
} 



@end
